package com.xiaochun.hxhj;


import android.Manifest;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bean.PublicVideoBean;
import com.fragment.HomeFragment;
import com.fragment.MineFragment;
import com.fragment.ReviewFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechUtility;
import com.myapp.MyApp;
import com.myview.PrivacyDialog;
import com.service.NotifationService;
import com.util.DensityUtil;
import com.util.DownUtil;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.PermissionUtils;
import com.util.RequestManager;
import com.util.ToastUtils;
import com.util.updateManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
//启动页一张图片3到5秒------视频页面（第一次）---首页---------（修改密码）

public class MainActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.main_container_content)
    FrameLayout main_container_content;
    @BindView(R.id.layout_title)
    LinearLayout layout_title;
    @BindView(R.id.ll_home)
    LinearLayout ll_home;
    @BindView(R.id.img_home)
    ImageView img_home;
    @BindView(R.id.tv_home)
    TextView tv_home;
    @BindView(R.id.ll_review)
    LinearLayout ll_review;
    @BindView(R.id.img_review)
    ImageView img_review;
    @BindView(R.id.tv_review)
    TextView tv_review;
    @BindView(R.id.ll_mine)
    LinearLayout ll_mine;
    @BindView(R.id.img_mine)
    ImageView img_mine;
    @BindView(R.id.tv_mine)
    TextView tv_mine;
    private List<Fragment> fragments;
    private FragmentManager fragmentManager;
    private boolean isExit = false;
    private String fragmentitem;
    private HomeFragment homeFragment;
    private ReviewFragment reviewFragment;
    private MineFragment mineFragment;
    private updateManager mUpdateManager;
    private String dateastr;
    private List<PublicVideoBean.DataBean> videoList = new ArrayList<>();
    public List<String> videourllist = new ArrayList<>();
    private PopupWindow mPopupWindowexit;
    private Handler handlerdelay;
    private Handler handlerdelaynotify;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        handlerdelay = new Handler();

        Intent intentOne = new Intent(this, NotifationService.class);
        startService(intentOne);
        getConfiger();
    }

    public void getDeviceId() {
        String deviceId = "";
        if (TextUtils.isEmpty(deviceId)){
            deviceId= UUID.randomUUID().toString();
        }
        myapp.setDeviceId(deviceId);
    }


    public void updateUtil() {
        String versionName = "0";
        try {
            PackageInfo packageInfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mUpdateManager = new updateManager(this, versionName, true);
        mUpdateManager.checkUpdateInfo();
    }

    @Override
    protected void initListener() {
        ll_home.setOnClickListener(this);
        ll_review.setOnClickListener(this);
        ll_mine.setOnClickListener(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        String isagree = sharedPreferences.getString("isagree", "");

        if (!"1".equals(isagree)) {
            showPrivacy();
        }
        changeTitle("首页");
        showRightView(false);
        hideTitleBar();
        fragmentManager = getSupportFragmentManager();
        fragments = new ArrayList<>();
        handlerdelaynotify = new Handler();
        handlerdelaynotify.postDelayed(new Runnable() {
            @Override
            public void run() {
                Calendar cal = Calendar.getInstance();
                int h = cal.get(Calendar.HOUR_OF_DAY);
                int mi = cal.get(Calendar.MINUTE);
                String tixingtime = sharedPreferences.getString("tixingtime", "08:00");
                String mtime = mi + "";
                if (mtime.length() < 2) {
                    mtime = "0" + mi;
                }
                String time = h + ":" + mtime;
                if (tixingtime.equals(time)) {
                    EventBus.getDefault().post(new InfoEventMessage("时间通知栏"));
                    handlerdelaynotify.postDelayed(this, 60000);
                } else {
                    handlerdelaynotify.postDelayed(this, 1000);
                }


            }
        }, 0);

    }


    /**
     * 显示用户协议和隐私政策
     */
    private void showPrivacy() {

        final PrivacyDialog dialog = new PrivacyDialog(MainActivity.this);
        TextView tv_privacy_tips = dialog.findViewById(R.id.tv_privacy_tips);
        TextView btn_exit = dialog.findViewById(R.id.btn_exit);
        TextView btn_enter = dialog.findViewById(R.id.btn_enter);
        dialog.show();
        String string = "  请你务必审慎阅读、充分理解\"服务协议”和“隐私政策”各条款，包括但不限于:为了向你提供内容展示，图片保存等服务，我们需要收集你的设备信息、操作日志等个人信息。你可以在“设置\"中查看、变更、删除个人信息并管理你的授权。你可阅读《服务协议》和《隐私政策》了解详细信息。如你同意，请点击“同意”开始接受我们的服务。";


        String key1 = "《服务协议》";
        String key2 = "《隐私政策》";
        int index1 = string.indexOf(key1);
        int index2 = string.indexOf(key2);

        //需要显示的字串
        SpannableString spannedString = new SpannableString(string);
        //设置点击字体颜色
        ForegroundColorSpan colorSpan1 = new ForegroundColorSpan(getResources().getColor(R.color.colorBlue));
        spannedString.setSpan(colorSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(getResources().getColor(R.color.colorBlue));
        spannedString.setSpan(colorSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置点击字体大小
        AbsoluteSizeSpan sizeSpan1 = new AbsoluteSizeSpan(14, true);
        spannedString.setSpan(sizeSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        AbsoluteSizeSpan sizeSpan2 = new AbsoluteSizeSpan(14, true);
        spannedString.setSpan(sizeSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        //设置点击事件
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                if (DensityUtil.isFastDoubleClick()) {
                    return;
                }
                Intent intent = new Intent(context, WebviewActivity2.class);
                intent.putExtra("type", "用户协议");
                intent.putExtra("url", "https://huiduji.bigchun.com/useragreement.html");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                //点击事件去掉下划线
                ds.setUnderlineText(false);
            }
        };
        spannedString.setSpan(clickableSpan1, index1, index1 + key1.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                if (DensityUtil.isFastDoubleClick()) {
                    return;
                }
                Intent intent = new Intent(context, WebviewActivity2.class);
                intent.putExtra("type", "隐私政策");
                intent.putExtra("url", "https://huiduji.bigchun.com/privarypolicy.html");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                //点击事件去掉下划线
                ds.setUnderlineText(false);
            }
        };
        spannedString.setSpan(clickableSpan2, index2, index2 + key2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

        //设置点击后的颜色为透明，否则会一直出现高亮
        tv_privacy_tips.setHighlightColor(Color.TRANSPARENT);
        //开始响应点击事件
        tv_privacy_tips.setMovementMethod(LinkMovementMethod.getInstance());

        tv_privacy_tips.setText(spannedString);

        //设置弹框宽度占屏幕的80%
        WindowManager m = getWindowManager();
        Display defaultDisplay = m.getDefaultDisplay();
        final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (int) (defaultDisplay.getWidth() * 0.80);
        dialog.getWindow().setAttributes(params);

        btn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sharedPreferences.edit().putString("isagree", "0").commit();
                finish();
            }
        });

        btn_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sharedPreferences.edit().putString("isagree", "1").commit();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if ( ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{ Manifest.permission.ACCESS_COARSE_LOCATION}, 10);
                    } else {
                        //获取到权限
                        getDeviceId();
                        getData();
                        getVideoData();
                    }
                }
                if (PermissionUtils.isGrantExternalRW(MainActivity.this, 1)) {
                    //登陆
                    updateUtil();
                }
                SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID + "=8fa6afb7");
                getDeviceId();

            }
        });

    }

    @Override
    protected void initData() {
        homeFragment = new HomeFragment();
        fragments.add(homeFragment);
        hideOthersFragment(homeFragment, true);
    }

    /**
     * 动态显示Fragment
     *
     * @param showFragment 要增加的fragment
     * @param add          true：增加fragment；false：切换fragment
     */
    private void hideOthersFragment(Fragment showFragment, boolean add) {
        FragmentTransaction transition = fragmentManager.beginTransaction();
        if (add) {
            transition.add(R.id.main_container_content, showFragment);
        }
        for (Fragment fragment : fragments) {
            if (showFragment.equals(fragment)) {
                transition.show(fragment);
            } else {
                transition.hide(fragment);
            }
        }
        transition.commit();
    }

    /**
     * 连按两次返回退出
     */
    public void doubleClickExit() {
        Timer timer = null;
        if (!isExit) {
            //设置退出条件为true
            isExit = true;
            //提示
            ToastUtils.show("再按一次退出");
            //启动计时器  2S内不点退出的话  就重置isExit的状态
            timer = new Timer();

            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
        } else {
            //退出app
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!"1".equals(fragmentitem)) {
                initBotton();
                img_home.setImageResource(R.mipmap.icon_subject_checked);
                tv_home.setTextColor(Color.parseColor("#FFAF06"));
                hideOthersFragment(homeFragment, false);
                fragmentitem = "1";
            } else {
                doubleClickExit();
            }


        }
        return false;
    }

    private void initBotton() {
        img_home.setImageResource(R.mipmap.icon_subject);
        img_review.setImageResource(R.mipmap.icon_review);
        img_mine.setImageResource(R.mipmap.icon_mine);
        tv_home.setTextColor(Color.parseColor("#9E9B9E"));
        tv_review.setTextColor(Color.parseColor("#9E9B9E"));
        tv_mine.setTextColor(Color.parseColor("#9E9B9E"));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_home:
                initBotton();
                img_home.setImageResource(R.mipmap.icon_subject_checked);
                tv_home.setTextColor(Color.parseColor("#FFAF06"));
                hideOthersFragment(homeFragment, false);
                fragmentitem = "1";
                break;
            case R.id.ll_review:
                initBotton();
                img_review.setImageResource(R.mipmap.icon_review_checked);
                tv_review.setTextColor(Color.parseColor("#FFAF06"));
                if (reviewFragment == null) {
                    reviewFragment = new ReviewFragment();
                    fragments.add(reviewFragment);
                    hideOthersFragment(reviewFragment, true);
                } else {
                    hideOthersFragment(reviewFragment, false);
                }
                fragmentitem = "2";
                break;
            case R.id.ll_mine:
                String token = getUserInfo("token");
                initBotton();
                img_mine.setImageResource(R.mipmap.icon_mine_checked);
                tv_mine.setTextColor(Color.parseColor("#FFAF06"));
                if (mineFragment == null) {
                    mineFragment = new MineFragment();
                    fragments.add(mineFragment);
                    hideOthersFragment(mineFragment, true);
                } else {
                    if ("".equals(token) || token == null) {
                        mineFragment = new MineFragment();
                        fragments.add(mineFragment);
                        hideOthersFragment(mineFragment, true);
                    } else {
                        hideOthersFragment(mineFragment, false);
                    }

                }
                fragmentitem = "3";
                break;

        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //检验是否获取权限，如果获取权限，外部存储会处于开放状态，会弹出一个toast提示获得授权
                    getDeviceId();
                    getData();
                    getVideoData();
                } else {
//                    showPermissionDialog();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 提示打开设置对话框
     */
    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);


        builder.setTitle("帮助");
        builder.setMessage("当前应用需要读手机状态权限。请点击\"设置\"-打开权限。");
        // 拒绝, 退出应用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });


        builder.setCancelable(false);
        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    public String CHANNEL_ID = "1";
    public String CHANEL_NAME = "课程提醒";

    public void showNotify() {
        NotificationChannel channel = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建 通知通道  channelid和channelname是必须的（自己命名就好）
            channel = new NotificationChannel(CHANNEL_ID, CHANEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.enableLights(true);//是否在桌面icon右上角展示小红点
            channel.setLightColor(Color.GREEN);//小红点颜色
            channel.setShowBadge(false); //是否在久按桌面图标时显示此渠道的通知
        }
        //调用NotificationCompat.Builder的setContentIntent()来添加PendingIntent
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification;
        //获取Notification实例   获取Notification实例有很多方法处理    在此我只展示通用的方法（虽然这种方式是属于api16以上，但是已经可以了，毕竟16以下的Android机很少了，如果非要全面兼容可以用）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //向上兼容 用Notification.Builder构造notification对象
            notification = new Notification.Builder(context, CHANNEL_ID).setContentTitle("中科慧学慧记").setContentText("训练时间到，赶快来提升自己的记忆力吧!").setContentIntent(pi).setWhen(System.currentTimeMillis()).setSmallIcon(R.mipmap.ic_launcher).setColor(Color.parseColor("#FEDA26")).setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)).setTicker("中科慧学慧记").setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).build();
        } else {
            //向下兼容 用NotificationCompat.Builder构造notification对象
            notification = new NotificationCompat.Builder(context).setContentTitle("中科慧学慧记").setContentText("训练时间到，赶快来提升自己的记忆力吧!").setWhen(System.currentTimeMillis()).setContentIntent(pi).setSmallIcon(R.mipmap.ic_launcher).setColor(Color.parseColor("#FEDA26")).setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)).setTicker("中科慧学慧记").setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).build();
        }


        //发送通知
        int notifiId = 1;
        //创建一个通知管理器
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.createNotificationChannel(channel);
        }
        notificationManager.notify(notifiId, notification);


    }

    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String message = event.getMessage();
        //0失败   1成功

        String sr = "";
        if ("时间通知栏".equals(message)) {
            MyLog.e("网页", "   EVENTBUS     ");
            showNotify();
        } else if ("登录签到".equals(message)) {
            getData();
        } else if ("设备ID已更新退出登录".equals(message)) {
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type, context, MainActivity.this, tv_home);
//            popbyexit(type);
        }


    }

    private void getData() {
        String token = getUserInfo("token");
        String url = myapp.getWebConfig() + "/api/score/sign";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        MyLog.e("每日签到", "token=" + token);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    msg.obj = jsonObject.getString("msg");
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void getVideoData() {
        String url = myapp.getWebConfig() + "/api/file_list/getList";
        HashMap<String, String> paramsMap = new HashMap<>();
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    videoList = new Gson().fromJson(data.toString(), new TypeToken<List<PublicVideoBean.DataBean>>() {
                    }.getType());
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void getConfiger() {
        String url = myapp.getWebConfig() + "/api/index/config";
        HashMap<String, String> paramsMap = new HashMap<>();
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
//                    "pay_status": "1",
//                            "pay_status_msg": "线上支付正在开通中...，请联系代理商",
//                            "yanchi_time": 1000
                    JSONObject data = jsonObject.getJSONObject("data");
                    String pay_status = data.getString("pay_status");
                    String pay_status_msg = data.getString("pay_status_msg");
                    String yanchi_time = data.getString("yanchi_time");
                    String banner_time = data.getString("banner_time");
                    String appid = data.getString("appid");
                    String appsecret = data.getString("appsecret");
                    String device_time = data.getString("device_time");


                    String wx_h5_link = data.getString("wx_h5_link");
                    String vip_price = data.getString("vip_price");
                    String is_fenxiang = data.getString("is_fenxiang");
                    String fenxiang_link = data.getString("fenxiang_link");
                    String is_viplink = data.getString("is_viplink");
                    String vip_link = data.getString("vip_link");
                    if ("".equals(device_time)) {
                        device_time = "3000";
                    }
                    myapp.setDevice_time(device_time);
                    myapp.setAppId(appid);
                    myapp.setAppSecret(appsecret);
                    myapp.setPay_status(pay_status);
                    myapp.setPay_status_msg(pay_status_msg);
                    myapp.setYanchi_time(yanchi_time);
                    myapp.setBanner_time(banner_time);
                    myapp.setVip_price(vip_price);
                    myapp.setIs_fenxiang(is_fenxiang);
                    myapp.setFenxiang_link(fenxiang_link);
                    myapp.setIs_viplink(is_viplink);
                    myapp.setVip_link(vip_link);
                    myapp.setWx_h5_link(wx_h5_link);
                    msg.arg1 = 5;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    break;
                case 1:
                    ToastUtils.show("网络错误，请稍后重试！");
                    break;
                case 2:
                    saveUserInfo("user_id", "");
                    saveUserInfo("username", "");
                    saveUserInfo("nickname", "");
                    saveUserInfo("mobile", "");
                    saveUserInfo("avatar", "");
                    saveUserInfo("score", "");
                    saveUserInfo("student_id", "");
                    saveUserInfo("is_bind_wx", "");
                    saveUserInfo("token", "");
                    saveUserInfo("is_agent", "");
                    saveUserInfo("vip_expire", "");
                    saveUserInfo("is_vip", "");
                    Intent intent = new Intent(context, LoginActivity.class);
                    startActivity(intent);
                    break;
                case 3:
                    saveUserInfo("sinedate", dateastr);
                    String obj1 = (String) msg.obj;
                    ToastUtils.show(obj1);
                    break;
                case 4:
                    int size = videoList.size();
                    videourllist.clear();
                    for (int i = 0; i < size; i++) {
                        String file = videoList.get(i).getFile();
                        int id = videoList.get(i).getId();
                        int version = videoList.get(i).getVersion();
                        String userInfo = getUserInfo(id + "=" + version);
                        if (userInfo == null || "".equals(userInfo)) {
                            String oneKey = getOneKey(userInfo);
                            clearSingleKey(oneKey);
                            saveUserInfo(id + "=" + version, file);
                            videourllist.add(file);
                        }
//                        String oneKeyForId = getOneKeyForId(musicid);//1=1
//                        String key = getUserInfo(oneKeyForId);//音频在线路径
//                        userInfo = getUserInfo(key);//vXX.mp3
                    }
                    new DownUtil(videourllist, context);

//                    new MyThread(2,context,videourllist).start();

                    break;
                case 5:
                    EventBus.getDefault().post(new InfoEventMessage("轮播图时间"));
                    String device_time = "";
//                    String device_time = MyApp.device_time;
                    if ("".equals(device_time)) {
                        device_time = "3000";
                    }
                    final String devicetime = device_time;
                    handlerdelay.postDelayed(new Runnable() {
                        @Override
                        public void run() {
//                            MyLog.e("服务执行定时任务","服务执行定时任务"+devicetime);
                            String token = sharedPreferences.getString("token", "");
                            if (!"".equals(token) && MyApp.isRequest) {
                                getDataDevice();
                            }
                            handlerdelay.postDelayed(this, Integer.parseInt(devicetime));


                        }
                    }, Integer.parseInt(devicetime));
                    break;
                case 6:
                    ToastUtils.show("收藏成功");
                    break;
                case 7:
//                    String str = (String) msg.obj;
//                    popbyexit(str);
                    break;
                case 11:
                    break;
                case 12:
                    break;
            }
        }
    };


    /**
     * 弹出退出页面搜索框
     */
    private void popbyexit(String str) {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_exit_app, null);

        TextView tv_des = popupWindow.findViewById(R.id.tv_des);
        tv_des.setText(str);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindowexit.dismiss();
//                logoutUser();
                saveUserInfo("user_id", "");
                saveUserInfo("username", "");
                saveUserInfo("nickname", "");
                saveUserInfo("mobile", "");
                saveUserInfo("avatar", "");
                saveUserInfo("score", "");
                saveUserInfo("student_id", "");
                saveUserInfo("is_bind_wx", "");
                saveUserInfo("token", "");
                saveUserInfo("is_agent", "");
                saveUserInfo("vip_expire", "");
                saveUserInfo("is_vip", "");
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);

            }
        });

        mPopupWindowexit = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindowexit.getWidth();
        int mPopupWindowHeight = mPopupWindowexit.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindowexit.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindowexit.setOutsideTouchable(true);
        mPopupWindowexit.setTouchable(true);
        mPopupWindowexit.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindowexit.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowexit.showAtLocation(tv_home, Gravity.BOTTOM, 0, Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowexit.showAtLocation(tv_home, Gravity.BOTTOM, 0, 0);
        }
        mPopupWindowexit.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    private void getDataDevice() {
        String token = sharedPreferences.getString("token", "");
        String url = MyApp.siteurl + "/api/user/device";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("device_id", myapp.getDeviceId());
        paramsMap.put("token", token);
        RequestManager.getInstance(this).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
//                MyLog.e("服务定时请求任务", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("123")) {
                        msg.obj = jsonObject.getString("msg");
                        String msg1 = jsonObject.getString("msg");
                        msg.arg1 = 7;
//                        handler.sendMessage(msg);
                        EventBus.getDefault().post(new InfoEventMessage("设备ID已更新退出登录", msg1));
                        MyApp.setIsRequest(false);
                    } else {
                        MyApp.setIsRequest(true);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyLog.e("主页面被销毁", "主页面被销毁");
    }
}
